import BackPage from '@/components/BackPage';
import SelectOne from '@/components/SelectOne';
import { allList } from '@/services/banned';
import { endBan } from '@/services/user';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { Button, message, Modal } from 'antd';
import moment from 'moment';
import { useCallback, useEffect, useRef, useState } from 'react';
import styles from './index.less';

const Users: React.FC = () => {
  const [actionModal, setActionModal] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const colorThem = localStorage.getItem('color') || '#1a7721';
  const [list, setList] = useState<any[]>([]);
  const [total, setTotal] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [banId, setBanId] = useState<string>('');
  const [selectList, setSelectList] = useState<any[]>([]);
  const disableState = [
    { key: '1', value: '仅禁止通话' },
    { key: '2', value: '仅禁止评论' },
    { key: '3', value: '禁止通话且禁止评论' },
  ];
  console.log(disableState);

  const columns: ProColumns<any>[] = [
    {
      dataIndex: 'index',
      valueType: 'indexBorder',
      width: 48,
    },
    {
      title: '买家编号',
      dataIndex: 'userid',
      copyable: true,
      ellipsis: true,
    },
    {
      title: '禁言类型',
      dataIndex: 'disable',
      ellipsis: true,
      render: (text, record) => [
        <div key={record.id}>
          {disableState.map((item: any) => {
            if (record.disable == item.key) {
              return <div key={record.id}>{item.value}</div>;
            } else {
              return;
            }
          })}
        </div>,
      ],
    },
    {
      title: '禁言原因',
      dataIndex: 'reason',
      ellipsis: true,
    },
    {
      title: '禁言时间',
      key: 'timeadd',
      render: (text, record) => [
        <div key={record.id}>{`${moment(Number(record.timeadd)).format(
          'YYYY-MM-DD HH:mm:ss',
        )}`}</div>,
      ],
    },
    {
      title: '解除时间',
      key: 'timeend',
      render: (text, record) => [
        <div key={record.id}>
          {record.timeend === null
            ? ''
            : `${moment(Number(record.timeend)).format('YYYY-MM-DD HH:mm:ss')}`}
        </div>,
      ],
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      align: 'center',
      render: (text, record) => [
        <div key={record.id} className={styles.action}>
          {record.timeend ? (
            '禁言已解除'
          ) : (
            <Button
              className={styles.delete}
              onClick={() => {
                setActionModal(true);
                setBanId(record.userid);
              }}
              style={{ border: `1px solid ${colorThem}`, color: colorThem }}
            >
              解除禁言
            </Button>
          )}
        </div>,
      ],
    },
  ];

  // 分页的方法
  const handlePageChange = (page: any) => {
    setCurrentPage(page);
  };

  const getList = useCallback(async () => {
    try {
      const res = await allList({ pageIndex: currentPage });
      setTotal(res.total);
      setList(res.list);
    } catch (error) {
      console.error(error);
    }
  }, [currentPage]);

  const endingBan = async () => {
    try {
      await endBan({ id: banId, disable: '0' }).then(() => {
        setActionModal(false);
        getList();
        message.success('解除禁言成功');
      });
    } catch (error) {
      console.log(error);
    }
  };
  useEffect(() => {
    getList();
  }, [getList]);

  return (
    <BackPage thisRoute={'/bannedPost'} lastRoute={'禁言管理'}>
      <div className={styles.container}>
        <SelectOne
          searchText={'买家编号'}
          fromWhere={'banned'}
          selected={(value) => {
            setSelectList(value);
          }}
          clear={() => {
            setSelectList([]);
          }}
        />
        <ProTable<any>
          columns={columns}
          dataSource={selectList.length !== 0 ? selectList : list}
          actionRef={actionRef}
          cardBordered={false}
          editable={{
            type: 'multiple',
          }}
          columnsState={{
            persistenceKey: 'pro-table-singe-demos',
            persistenceType: 'localStorage',
            onChange(value) {
              console.log('value: ', value);
            },
          }}
          rowKey="id"
          search={false}
          options={false}
          pagination={{
            total,
            current: currentPage, // 当前页数
            pageSize: 10, // 每页条数
            size: 'small', // 分页的样式
            hideOnSinglePage: true, // 只有一页时是否隐藏分页器
            onChange: handlePageChange, // 分页的方法
          }}
          dateFormatter="string"
          headerTitle=""
        />
        <Modal
          visible={actionModal}
          onCancel={() => {
            setActionModal(false);
          }}
          footer={[
            <>
              <Button
                onClick={() => {
                  setActionModal(false);
                }}
                className={styles.btnCancel}
              >
                取消
              </Button>
              <Button
                className={styles.btnSeal}
                style={{ background: `${colorThem}`, width: 120, color: '#fff' }}
                htmlType="submit"
                type="primary"
                onClick={endingBan}
              >
                确定
              </Button>
            </>,
          ]}
        >
          <div className={styles.actionContent}>
            <div style={{ fontSize: 15 }}>确定解除禁言吗</div>
          </div>
        </Modal>
      </div>
    </BackPage>
  );
};
export default Users;
